//
//  PhotoViewController.m
//  Shows
//
//  Created by Roc on 11-4-13.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "PhotoViewController.h"
#import "PhotoView.h"

@implementation PhotoViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.wantsFullScreenLayout = YES;
        self.hidesBottomBarWhenPushed = YES;
        
        _visiblePages = [[NSMutableSet alloc] init];
        _recycledPages = [[NSMutableSet alloc] init];
    }
    return self;
}

- (void)dealloc
{
    [_visiblePages release];
    _visiblePages = nil;
    [_recycledPages release];
    _visiblePages = nil;
    
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark -
#pragma mark pages layout

- (PhotoView *)dequeueRecycledPage
{
    PhotoView *page = [_recycledPages anyObject];
    if (page) {
        [[page retain] autorelease];
        [_recycledPages removeObject:page];
    }
    return page;
}

- (BOOL)isDisplayingPageForIndex:(NSUInteger)index
{
    BOOL foundPage = NO;
    for (PhotoView *page in _visiblePages) {
        if (page.index == index) {
            foundPage = YES;
            break;
        }
    }
    return foundPage;
}

- (CGRect)frameForPageAtIndex:(NSUInteger)index {
    CGRect bounds = _scrollView.bounds;
    CGRect pageFrame = bounds;
    //pageFrame.size.width -= (2 * 10);
    pageFrame.origin.x = (bounds.size.width * index);// + 10;
    return pageFrame;
}

- (void)configurePage:(PhotoView *)page forIndex:(NSUInteger)index
{
    page.index = index;
    [page load:[_photos objectAtIndex:index]];
    page.frame = [self frameForPageAtIndex:index];
}


///////////////////////////////////////////////////////////////////////////////////
// 计算当前可视页面,并对当前页面的前一和后一页面进行缓存
- (void)calcPages {
    // Calculate which pages are visible
    CGRect visibleBounds = _scrollView.bounds;
    int firstNeededPageIndex = floorf(CGRectGetMinX(visibleBounds) / CGRectGetWidth(visibleBounds));
    int lastNeededPageIndex  = floorf((CGRectGetMaxX(visibleBounds)+1) / CGRectGetWidth(visibleBounds));
    firstNeededPageIndex = MAX(firstNeededPageIndex, 0);
    lastNeededPageIndex  = MIN(lastNeededPageIndex, _photos.count - 1);
    
    // Recycle no-longer-visible pages 
    for (PhotoView* page in _visiblePages) {
        if (page.index < firstNeededPageIndex || page.index > lastNeededPageIndex) {
            NSLog(@"Recycled Page:%d", page.index);
            [_recycledPages addObject:page];
            [page removeFromSuperview];
        }
    }
    [_visiblePages minusSet:_recycledPages];
    
    // add missing pages
    for (int index = firstNeededPageIndex; index <= lastNeededPageIndex; index++) {
        if (![self isDisplayingPageForIndex:index]) {
            PhotoView *page = [self dequeueRecycledPage];
            if (page == nil) {
                page = [[[PhotoView alloc] init] autorelease];
                page.contentMode = UIViewContentModeScaleAspectFit;
                NSLog(@"add new page:%d", index);
            } else {
                [page clean]; //清理数据和从新绘制
            }
            [self configurePage:page forIndex:index];
            [_scrollView addSubview:page];
            [_visiblePages addObject:page];
        }
    }    
}


#pragma mark - View lifecycle

// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
    NSLog(@"PhotoViewController loadView");
    [super loadView];
    
    CGRect screenFrame = [UIScreen mainScreen].bounds;
    
    _scrollView = [[UIScrollView alloc] initWithFrame:screenFrame];
    _scrollView.delegate = self;
    _scrollView.pagingEnabled = YES;
    _scrollView.contentSize = CGSizeMake(screenFrame.size.width*_photos.count, screenFrame.size.height);
    _scrollView.backgroundColor = [UIColor blackColor];
    
    [self calcPages];
    
    [self.view addSubview:_scrollView];
}


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    NSLog(@"PhotoViewController viewDidLoad");
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (id)initWithPhoto:(NSMutableArray*)photos {
    self = [self initWithNibName:nil bundle:nil];
    
    if(self) {
        _photos = [photos retain]; 
    }
    
    return self;
}


#pragma mark -
#pragma mark ScrollView delegate methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self calcPages];
}

@end
